package com.qf.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zjw
 * @description 认证过滤器
 * @date 2021/11/11 17:45
 */
@Component
public class AuthenticationFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        // 推荐采用常量中提供的过滤器顺序进行加，减操作设置顺序
        // PRE_DECORATION_FILTER_ORDER = 5，是Zuul自带的前缀过滤器的最后一个过滤器
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1000;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //业务： 请求参数中必须携带token=123的参数，如果不带，视为权限不足，返回401状态码、

        //1. 获取Request对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        //2. 获取参数
        String token = request.getParameter("token");

        //3. 判断参数书否合法
        if(!"123".equalsIgnoreCase(token)) {
            //4. 如果不等于123，代表不合法，直接返回401状态码
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
        }

        // 返回结果没有任何意义，可以直接不管
        return null;
    }
}
